package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.DeviceImage;
import com.example.mapper.DeviceImageMapper;
import com.example.service.DeviceImageService;
import com.example.vo.DeviceImageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 设备图片业务逻辑层实现类
 *
 * @author system
 * @since 2024-01-01
 */
@Service
@Slf4j
public class DeviceImageServiceImpl extends ServiceImpl<DeviceImageMapper, DeviceImage> implements DeviceImageService {
    
    // 文件上传目录
    private static final String UPLOAD_DIR = "uploads/device-images/";
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceImageVO uploadImage(MultipartFile file, String imageName, Long groupId, String operator) {
        try {
            // 检查文件
            if (file.isEmpty()) {
                log.warn("上传文件为空");
                return null;
            }
            
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                log.warn("文件名不能为空");
                return null;
            }
            
            String fileExtension = getFileExtension(originalFilename);
            if (!isValidImageType(fileExtension)) {
                log.warn("不支持的文件类型：{}", fileExtension);
                return null;
            }
            
            // 检查文件大小（2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                log.warn("文件大小超过限制：{} bytes", file.getSize());
                return null;
            }
            
            // 创建上传目录
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + "." + fileExtension;
            Path filePath = uploadPath.resolve(fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), filePath);
            
            // 保存到数据库
            DeviceImage deviceImage = new DeviceImage();
            deviceImage.setImageName(imageName != null ? imageName : originalFilename);
            deviceImage.setFileName(fileName);
            deviceImage.setFilePath(filePath.toString());
            deviceImage.setFileSize(file.getSize());
            deviceImage.setFileType(file.getContentType());
            deviceImage.setImageUrl("/api/device-image/" + fileName + "/view");
            deviceImage.setGroupId(groupId);
            deviceImage.setCreateTime(LocalDateTime.now());
            deviceImage.setCreateBy(operator);
            deviceImage.setUpdateTime(LocalDateTime.now());
            deviceImage.setUpdateBy(operator);
            
            boolean success = this.save(deviceImage);
            if (success) {
                log.info("设备图片上传成功，ID：{}，名称：{}", deviceImage.getId(), deviceImage.getImageName());
                return convertToVO(deviceImage, ""); // 分组名称由Controller层填充
            } else {
                // 删除已上传的文件
                Files.deleteIfExists(filePath);
                log.error("保存设备图片到数据库失败");
                return null;
            }
        } catch (Exception e) {
            log.error("上传设备图片失败", e);
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteImage(String id) {
        try {
            // 检查图片是否存在
            DeviceImage image = this.getById(id);
            if (image == null) {
                log.warn("设备图片不存在，ID：{}", id);
                return false;
            }
            
            // 删除文件
            Path filePath = Paths.get(image.getFilePath());
            Files.deleteIfExists(filePath);
            
            // 删除数据库记录
            boolean result = this.removeById(id);
            if (result) {
                log.info("设备图片删除成功，ID：{}，名称：{}", id, image.getImageName());
            }
            return result;
        } catch (Exception e) {
            log.error("删除设备图片失败", e);
            return false;
        }
    }

    @Override
    public List<DeviceImageVO> getImagesByGroupId(Long groupId) {
        try {
            // 查询该分组下的所有图片
            List<DeviceImage> images = this.list(
                new LambdaQueryWrapper<DeviceImage>()
                    .eq(DeviceImage::getGroupId, groupId)
                    .orderByAsc(DeviceImage::getId)
            );
            
            // 转换为VO（分组名称由Controller层填充）
            return images.stream()
                .map(image -> convertToVO(image, ""))
                .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("根据分组ID获取设备图片失败", e);
            return null;
        }
    }

    @Override
    public List<DeviceImageVO> getAllImages() {
        try {
            // 获取所有图片
            List<DeviceImage> images = this.list(
                new LambdaQueryWrapper<DeviceImage>()
                    .orderByDesc(DeviceImage::getCreateTime)
            );
            
            // 转换为VO（分组名称由Controller层填充）
            return images.stream()
                .map(image -> convertToVO(image, ""))
                .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取所有设备图片失败", e);
            return null;
        }
    }
    
    /**
     * 实体对象转换为VO对象
     * 
     * @param image 设备图片实体
     * @param groupName 分组名称
     * @return 设备图片VO对象
     */
    private DeviceImageVO convertToVO(DeviceImage image, String groupName) {
        DeviceImageVO vo = new DeviceImageVO();
        BeanUtils.copyProperties(image, vo);
        vo.setGroupName(groupName);
        return vo;
    }
    
    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex + 1).toLowerCase() : "";
    }
    
    /**
     * 检查是否为有效的图片类型
     */
    private boolean isValidImageType(String extension) {
        return "svg".equals(extension) || "png".equals(extension) || 
               "jpg".equals(extension) || "jpeg".equals(extension);
    }
} 